<!--
 * @Author: jingjingzheng 1742420988@qq.com
 * @Date: 2023-12-10 14:18:07
 * @LastEditors: zhengjingjing 1742420988@qq.com
 * @LastEditTime: 2024-10-22 17:11:32
 * @FilePath: \mdbj-ui\src\views\statistics\roadfunction\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container" style="overflow:scroll">
    <el-row>
      <!-- 查询条件-->
      <el-form ref="form" :model="queryParams" label-width="80px" size="small" :inline="true" class="queryPanel">
        <!-- 按保洁单位查询 -->
        <el-form-item label="保洁单位">
          <el-select v-model="queryParams.cleancompany" placeholder="请选择保洁单位" style="width: 10vw" clearable>
            <el-option v-for="dict in dict.type.sys_cleancompany" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="道路等级">
          <el-select v-model="queryParams.roadclass_js" placeholder="请选择道路等级" style="width: 10vw" clearable>
            <el-option v-for="dict in dict.type.sys_roadclass_js" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.data_status" placeholder="请选择道路状态" style="width: 10vw" clearable>
            <el-option v-for="dict in dict.type.road_data_status" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">统计</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['result:export']"
          >导出</el-button>
        </el-form-item>
        <el-switch v-model="statisticsway" style="height: 33px" active-text="按道路等级统计" active-color="#13ce66"
          @change="switchChange">
        </el-switch>
      </el-form>
    </el-row >

    <div v-if="totalfeatures !== undefined" class="totalstyle" :style="{ color: theme }">
      <span>道路总长度：{{totalfeatures.length}}m</span>
      <span>机动车道总面积：{{totalfeatures.motorway}}m²</span>
      <span>非机动车道总面积：{{totalfeatures.nonmotorway}}m²</span>
      <span>人行道总面积：{{totalfeatures.sidewalk}}m²</span>
      <span>门前总面积:{{totalfeatures.frontarea}}m²</span>
    </div>

    <!-- 显示道路编码查询结果表单 -->
    <el-table :data="features" v-loading="loading" stripes highlight-current-row :height="tableHeight">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" type="index" width="50"> </el-table-column>
      <el-table-column v-if="!statisticsway" :key="Math.random()" label="道路编码" align="center" :show-overflow-tooltip="true"
        prop="code"></el-table-column>
      <el-table-column v-if="!statisticsway" :key="Math.random()" label="道路名称" align="center" :show-overflow-tooltip="true"
        prop="name"></el-table-column>
      <el-table-column label="道路等级" align="center" :show-overflow-tooltip="true" prop="roadclass_js">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_roadclass_js" :value="scope.row.roadclass_js" />
        </template>
      </el-table-column>
      <el-table-column label="道路长度(m)" align="center" :show-overflow-tooltip="true" prop="length">
        <template slot-scope="scope">
          {{ scope.row.length}}
        </template>
      </el-table-column>
      <el-table-column v-if="!statisticsway" :key="Math.random()" label="宽度（参考值）" width="120" align="center" :show-overflow-tooltip="true"
        prop="width"></el-table-column>
      <el-table-column v-if="!statisticsway" :key="Math.random()" label="起点" align="center" :show-overflow-tooltip="true"
        prop="startpoint"></el-table-column>
      <el-table-column v-if="!statisticsway" :key="Math.random()" label="止点" align="center" :show-overflow-tooltip="true"
        prop="endpoint"></el-table-column>
      <el-table-column label="机动车道面积(m²)" align="center" :show-overflow-tooltip="true"
        prop="motorway"></el-table-column>
      <el-table-column label="非机动车道面积(m²)" align="center" :show-overflow-tooltip="true"
        prop="nonmotorway"></el-table-column>
      <el-table-column label="人行道面积(m²)" align="center" :show-overflow-tooltip="true"
        prop="sidewalk"></el-table-column>
      <el-table-column label="门前面积(m²)" align="center" :show-overflow-tooltip="true"
        prop="frontarea"></el-table-column>
      <el-table-column v-if="!statisticsway" :key="Math.random()" label="保洁公司" align="center" :show-overflow-tooltip="true"
        prop="cleancompany"></el-table-column>
      <el-table-column v-if="!statisticsway" :key="Math.random()" label="原路名" align="center" :show-overflow-tooltip="true"
        prop="oldname"></el-table-column>
      <el-table-column v-if="!statisticsway" :key="Math.random()" label="状态" align="center" :show-overflow-tooltip="true" prop="data_status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.road_data_status" :value="scope.row.data_status" />
          </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      layout="total, sizes,prev, pager, next" @pagination="getList" />

    <!-- 统计 -->
    <div class="echart-dom" >
      <div class="echart-title">
        <div class="titleborder" :style="{ background: theme }">
          <div class="divider"></div>
          <div class="tltle">道路情况统计</div>
        </div>
      </div>
      <div id="domCart1"></div>
      <div id="domCart2"></div>
    </div>
  </div>
</template>

<script>
import FeatureLayer from "@arcgis/core/layers/FeatureLayer";
import { getRoadStatistics, getRoadClassStatistics, getRoadSumStatistics } from "../../../api/statistics/road";
import * as echarts from "echarts";
import { getDicts } from "../../../api/system/dict/data";
import { EleResize } from "@/utils/esresize"; // 图表自适应

export default {
  components: {
    FeatureLayer,
  },
  dicts: [
    "sys_roadclass_js",
    "sys_cleancompany",
    "road_data_status"
  ],
  computed: {
    theme() {
      return this.$store.state.settings.theme;
      },
  },
  data() {
    return {
      // 显示统计方式：FALSEL:按照道路编码统计，true：按照道路等级统计
      statisticsway: false,
      // 是否显示统计图
      isshowChart:undefined,
      // 表格高度
      tableHeight: "70vh",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        cleancompany: undefined,
        roadclass_js: null,
        data_status: null,
      },
      // 当前页要素集合
      features: [],
      classfeatures: [],
      // 当前查询要素总计
      totalfeatures: [],
      // 总条数
      total: 0,
      // 遮罩层
      loading: false,
      //统计类型,默认为按道路编码统计
      totaltype:1,
      // 统计图表
      // chartData1: [],
      chartData2: [],
    }
  },
  created() {
    let _self = this;
    _self.getList();
    _self.isshowChart = '1'

  },
  methods: {
    /**
    * @description: 切换道路编码和道路等级
    * @param {*} val
    * @return {*}
    */
    switchChange(val) {
      let _self = this;
      console.log(val);
      if (!val) {
        _self.totaltype = 1;
        _self.tableHeight = "70vh"
        _self.getData();
        _self.Chart2Data();
      } else {
        _self.totaltype = 2;
        _self.getclassData();
      };
    },
    getList() {
      let _self = this;
      // console.log(_self.queryParams);
      if (!_self.statisticsway) {
        _self.getData();
        _self.Chart2Data();
      } else _self.getclassData();
    },
    // 按道路编码统计全部道路长度、面积信息
    async getData() {
      let _self = this;
      _self.loading = true;
      // 先构建用于查询数据总条数的查询参数对象
      let queryParams = {
        cleancompany: _self.queryParams.cleancompany,
        roadclass_js: _self.queryParams.roadclass_js,
        data_status: _self.queryParams.data_status,
        returncountonly: "true"
      };
      // 首先查询数据总条数用于渲染分页组件值
      const codeResnum = await getRoadStatistics(queryParams);
      _self.total = parseInt(codeResnum.data.count)
      console.log(codeResnum)
      // 分页查询并在表格展示数据
      queryParams = {
        cleancompany: _self.queryParams.cleancompany,
        roadclass_js: _self.queryParams.roadclass_js,
        data_status: _self.queryParams.data_status,
        returecountonly: "false",
        pagesize: _self.queryParams.pageSize,
        pagenum: _self.queryParams.pageNum
      };
      // 查询数据
      const codeRes = await getRoadStatistics(queryParams);
      if (codeRes.code != 200 && codeRes.data.length == 0)
        return this.$message.error("按道路编码统计道路功能面积失败，请联系管理员！");
      console.log(codeRes)
      _self.features = codeRes.data
      _self.gettotal(queryParams);
      _self.loading = false
    },
    // 按道路等级统计全部道路长度、面积信息
    async getclassData() {
      let _self = this;
      _self.loading = true;
      // 先构建用于查询数据总条数的查询参数对象
      let queryParams = {
        cleancompany: _self.queryParams.cleancompany,
        roadclass_js: _self.queryParams.roadclass_js,
        data_status: _self.queryParams.data_status,
        returncountonly: "true"
      };
      // 首先查询数据总条数用于渲染分页组件值
      const classResnum = await getRoadClassStatistics(queryParams);
      _self.total = parseInt(classResnum.data.count)
      console.log(classResnum)
      // 分页查询并在表格展示数据
      queryParams = {
        cleancompany: _self.queryParams.cleancompany,
        roadclass_js: _self.queryParams.roadclass_js,
        data_status: _self.queryParams.data_status,
        returecountonly: "false",
        pagesize: _self.queryParams.pageSize,
        pagenum: _self.queryParams.pageNum
      };
      _self.features = []
      // 查询数据
      const classRes = await getRoadClassStatistics(queryParams);
      if (classRes.code != 200 && classRes.data.length == 0)
        return this.$message.error("按道路等级统计道路功能面积失败，请联系管理员！");
      console.log(classRes);
      this.$nextTick(() => {
        _self.features = classRes.data
      });
      _self.classfeatures = [];
      this.$nextTick(() => {
        _self.classfeatures = classRes.data
      });
      _self.gettotal(queryParams);
      console.log("getRoadClassStatistics", _self.features);
      _self.initChart2();
      _self.loading = false
    },
    // 统计道路总长度、总面积信息
    async gettotal(queryParams) {
      let _self = this;
      // 查询数据
      const totalResSum = await getRoadSumStatistics(queryParams);
      if (totalResSum.code != 200 && totalResSum.data.length == 0)
        return this.$message.error("统计道路功能面积失败，请联系管理员！");
      console.log(totalResSum);
      _self.totalfeatures = totalResSum.data[0];
      console.log(_self.totalfeatures);
      _self.initChart1();
    },
     /**
     * @description: 导出数据
     * @return {*}
     */
     handleExport() {
      let _self = this;
      let apiAddress=undefined;
      let exportdataname=undefined;
      if (_self.totaltype == 1) {
        exportdataname="按道路编码统计数据"
        apiAddress='road/statistics/getRoadStatistics';
      } else if(_self.totaltype == 2){
        exportdataname="按道路等级统计数据"
        apiAddress='road/statistics/getRoadClassStatistics';
      };
      let  exportParams = {
        cleancompany: _self.queryParams.cleancompany,
        roadclass_js: _self.queryParams.roadclass_js,
        data_status: _self.queryParams.data_status,
        isexport: 1,
        pagesize: 100000,
        pagenum: _self.queryParams.pageNum
      };
      this.downloadNode(
        apiAddress,
        {
          ...exportParams,
        },
        `${exportdataname}_${new Date().getTime()}.xlsx`
      );
    },
    /**
     * @description: 初始化统计图1
     * @return {*}
     */
    initChart1(){
      let _self = this;
      let chartData =  [
              _self.totalfeatures.length,
              _self.totalfeatures.motorway,
              _self.totalfeatures.nonmotorway,
              _self.totalfeatures.sidewalk,
              _self.totalfeatures.frontarea
          ];
      let chartDom = document.getElementById('domCart1')
      let myChart1 = echarts.init(chartDom);
      // 图表自适应
      const listener = function () {
        myChart1.resize();
      };
      EleResize.on(domCart1, listener);
      let option;
      app.config = {
        position: "top",
        distance: 20,
        onChange: function () {
          const labelOption = {
            position: app.config.position,
            distance: app.config.distance,
          };
          myChart1.setOption({
            series: [
              {
                label: labelOption,
              },
            ],
          });
        },
      };
      const labelOption = {
        show: true,
        position: app.config.position,
        formatter: "{c}  {name|{a}}",
        color: "black",
        rich: {
          name: {},
        },
      };
      option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
            crossStyle: {
              color: '#999'
            }
          },
          formatter: (params) => {
            let unit_name=undefined
            if(params[0].name =="道路长度"){
              unit_name=" m"
            }else{unit_name=" m²"}
            return (
              params[0].name +
              "<br>" +
              params[0].marker +
              " " +
              params[0].seriesName +
              ": " +
              params[0].data +" "+
              unit_name
            );
          },
        },
        toolbox: {
          feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        xAxis: [
          {
            type: "category",
            axisTick: { show: false },
            data:  ["道路长度","机动车道面积","非机动车道面积","人行道面积","门前面积"],
            boundaryGap: true,//x轴两边留空白
            axisLabel: {
              interval: 0, //代表显示所有x轴标签显示
              color: "black",
            },
          },
        ],
        yAxis: [
        {
            type: "value",
            name: "m/ m²",
            nameTextStyle:{
            },
            axisLabel: {
              formatter: function(v) {
                return v.toFixed(0); //0表示小数为0位，1表示1位小数，2表示2位小数
              },
            }
          },
        ],
        series: [
          {
            name: "",
            type: "bar",
            label: labelOption,
            emphasis: {
              focus: "series",
            },
            data:chartData
          },
        ],
      };
      option && myChart1.setOption(option);
    },
    // 按道路等级统计全部道路长度、面积信息
    async Chart2Data() {
      let _self = this;
      // 先构建用于查询数据的查询参数对象
      let queryParams = {
        cleancompany: _self.queryParams.cleancompany,
        roadclass_js: _self.queryParams.roadclass_js,
        data_status: _self.queryParams.data_status,
        returecountonly: "false",
        pagesize: _self.queryParams.pageSize,
        pagenum: _self.queryParams.pageNum
      };
      const classRes = await getRoadClassStatistics(queryParams);
      if (classRes.code != 200 && classRes.data.length == 0)
        return this.$message.error("按道路等级统计道路功能面积失败，请联系管理员！");
      _self.classfeatures = [];
      _self.classfeatures = classRes.data
      console.log(_self.classfeatures);
      _self.initChart2();
    },
    /**
     * @description: 初始化统计图2
     * @return {*}
     */
    async initChart2(){
      let _self = this;
      console.log(_self.classfeatures);
      let xAxisArr = [];
      let chartData1 = [];
      let chartData2 = [];
      let chartData3 = [];
      let chartData4 = [];
      let chartData5 = [];
      const labelOption = {
        show: true,
        position: 'top'
      };
      // 利用字典方法获取道路等级中所有数据
      const dictRes = await getDicts("sys_roadclass_js");
      if (dictRes.code != 200 && dictRes.data.length == 0)
        return this.$message.error("字典获取失败，请联系管理员！");
      console.log(dictRes);
      for (let index = 0; index < _self.classfeatures.length; index++) {
        const element = _self.classfeatures[index];
        const newDicts = dictRes.data.filter(
          (dictItem) => dictItem.dictValue === element.roadclass_js
        );
        let roadclassName =
          newDicts.length == 0
            ? element.roadclass_js
            : newDicts[0].dictLabel;
        // 存放道路等级中文名称
        xAxisArr.push(roadclassName);
        // 存放对应的道路长度
        chartData1.push(element.length);
        // 存放对应的道路面积
        // chartData2.push((element.motorway/10000).toFixed(2));
        chartData2.push(element.motorway);
        chartData3.push(element.nonmotorway);
        chartData4.push(element.sidewalk);
        chartData5.push(element.frontarea);
      };
      function _getMinValue(arr) {
        const max = Math.min(...arr);
        // 这样处理是为了不让最大值刚好到坐标轴最顶部
        return Math.ceil(max / 12) * 10;
      };
      function _getMaxValue(arr) {
        const max = Math.max(...arr);
        // 这样处理是为了不让最大值刚好到坐标轴最顶部
        return Math.ceil(max / 9.5) * 10;
      };
      let min1 = _getMinValue(chartData1);
      let min2 = _getMinValue(chartData2);
      let max1 = Math.ceil(_getMaxValue(chartData1)/10000)*10000;
      let max2 = Math.ceil(_getMaxValue(chartData2)/10000)*10000;
      var chartDom2 = document.getElementById('domCart2');
      var myChart2 = echarts.init(chartDom2);
      // 图表自适应
      const listener = function () {
        myChart2.resize();
      };
      EleResize.on(domCart2, listener);
      var option2;
      option2 = {
        tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999'
          }
          }
        },
        toolbox: {
          feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        legend: {
          data: ['道路长度', '机动车道面积', '非机动车道面积','人行道面积','门前面积']
        },
        xAxis: [
        {
          type: 'category',
          data: xAxisArr,
          boundaryGap: true,//x轴两边留空白
          interval: 1,
          axisPointer: {
            type: 'shadow'
          }
        }
        ],
        yAxis: [
        {
          type: 'value',
          name: ' m',
          min: 0,
          max: max1,
          interval: max1/10,
          axisLabel: {
            formatter: '{value}'
          }
        },
        {
          type: 'value',
          name: ' m²',
          min: 0,
          max: max2,
          interval: max2/10,
          axisLabel: {
          formatter: '{value} '
          }
        }
      ],
      series: [
        {
          name: '道路长度',
          type: 'bar',
          label: labelOption,
          tooltip: {
            valueFormatter: function (value) {
              return value + ' m';
            }
          },
          data: chartData1
        },
        {
          name: '机动车道面积',
          type: 'bar',
          yAxisIndex: 1,
          label: labelOption,
          tooltip: {
            valueFormatter: function (value) {
              return value + ' m²';
            }
          },
          data:chartData2
        },
        {
          name: '非机动车道面积',
          type: 'bar',
          yAxisIndex: 1,
          label: labelOption,
          tooltip: {
            valueFormatter: function (value) {
              return value + ' m²';
            }
          },
          data: chartData3
        },
        {
          name: '人行道面积',
          type: 'bar',
          yAxisIndex: 1,
          label: labelOption,
          tooltip: {
            valueFormatter: function (value) {
              return value + ' m²';
            }
          },
          data: chartData4
        },
        {
          name: '门前面积',
          type: 'bar',
          yAxisIndex: 1,
          label: labelOption,
          tooltip: {
            valueFormatter: function (value) {
              return value + ' m²';
            }
          },
          data: chartData5
        }
      ]
    };
      option2 && myChart2.setOption(option2);
    },
    /**
     * @description: 重置查询条件
     * @return {*}
     */
    resetQuery() {
      console.log('resetQuery');
      let _self = this;
      _self.queryParams.pageNum = 1;
      _self.queryParams.pageSize = 20;
      _self.queryParams.cleancompany = undefined;
      _self.queryParams.roadclass_js = undefined;
      _self.whereClause = undefined;
      _self.getList();
    },
    /**
     * @description: 查询按钮
     * @return {*}
     */
    handleQuery() {
      let _self = this;
      this.queryParams.pageNum = 1;
      _self.getList();
    },

  },
}
</script>

<style lang="scss" scoped>
.totalstyle{
  display: flex;
  justify-content: center;
  align-items: center;
  height: 5vh;
  margin-bottom: 1vh;
  background-color:#F8F8F9;
  font-size:18px;
  font-weight:bold;
  color:#409EFF;
  span{
    /* color:#515A6E; */
    margin-left: 5vh;
    margin-right: 5vh;
  }
}
#domCart1 {
  left: 5px;
  width: 100%;
  height: 50%;
  padding: 15px;
}
#domCart2 {
  left: 5px;
  width: 100%;
  height: 50%;
  padding: 15px;
}
.echart-dom {
  //height: 32%;
  margin-bottom: 10px;
  height: 100%;
  width: 100%;
}

.echart-title {
  padding-bottom: 2px;
  //   padding-top: 2px;
  //margin-left: -6px;
  width: 100%;
  //   padding-left: 4px;
  height: 38px;
  font-size: 16px;
  font-family: Source Han Sans CN-Regular, Source Han Sans CN;
  font-weight: 400;
  color: #ffffff;
  line-height: 24px;
  display: flex;
  align-content: center;
  align-items: center;
}

.titleborder {
  padding-left: 16px;
  width: inherit;
  height: 38px;
  /* background: -webkit-gradient(linear, left top, right top, from(#008cce), to(#1b678b)); */
  background: linear-gradient(90deg, #1890ff 0%, #1890ffc7 100%);
  opacity: 1;
  display: flex;
}

.divider {
  width: 4px;
  height: 18px;
  background: #ffffff;
  opacity: 1;
  margin-top: 9px;
  margin-left: 8px;
}

.tltle {
  height: 24px;
  font-size: 16px;
  font-family: Source Han Sans CN-Regular, Source Han Sans CN;
  font-weight: 400;
  color: #ffffff;
  margin-top: 6px;
  margin-left: 8px;
}
</style>
